import { Component, OnInit } from '@angular/core';
import {MsgResult} from "../../../../models/msg-result";
import {Path} from "../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {Router, ActivatedRoute} from "@angular/router";
import {PageSubject} from "../../../../util/page-subject";
import {OneDialogService} from "../../../../widgets/one-dialog/one-dialog.service";
import {ResponseUtil} from "../../../../util/response-util";
import {RolesService} from "../roles.service";
import {Role} from "../role";
import {MsgConstants} from "../../../../constants/constants";

declare var $;
@Component({
  selector: 'app-role-authorized',
  templateUrl: './role-authorized.component.html'
})
export class RoleAuthorizedComponent implements OnInit {
  role: Role;
  //角色授权数组
  role_authorty_id: Array<string> = [];

  roleId: string;

  menuId :string;
  //所有权限数组
  allAuthority: Array<string> = [];

  roleAuthority: Array<string> = [];
  //处理后的权限树
  menuAuthorityTree: Array<string> = [];

  constructor(
    private router: Router,
    private route: ActivatedRoute,
    private pageSubject: PageSubject,
    private dialogService: OneDialogService,
    private responseUtil: ResponseUtil,
    private rolesService: RolesService) {
    this.initObject();
  }

  ngOnInit() {
    //初始化导航
    this.pushPage();
    if (!!this.route.snapshot.params["roleId"]) {
      this.roleId = this.route.snapshot.params["roleId"];
    }
    //账户中角色授权,aRId:角色id；
    if (!!this.route.snapshot.params["aRId"]) {
      this.accountPushPage();
      this.menuId = this.route.snapshot.params["mid"];
      this.roleId = this.route.snapshot.params["aRId"];
    }
    //初始化菜单树
    this.initMenuZTree(this.roleId);

  }

  /**
   * 面包屑导航
   */
  pushPage() {
    let path = new Path("权限系统", "");
    this.pageSubject.pushPage("角色管理", "角色授权", path);
  }

  /**
   * 面包屑导航
   */
  accountPushPage() {
    let path = new Path("权限系统", "");
    this.pageSubject.pushPage("账户管理", "角色授权", path);
  }

  /**
   * 初始化各种权限id（菜单）
   */
  initMenuZTree(roleId) {
    this.rolesService.doAssignAuthority(roleId).subscribe(
      result => this.responseUtil.success(result, this.processMenuTreeResult),
      message => this.responseUtil.error(message)
    );
  }


  /**
   * 获取添加日志
   * @param result
   */
  private processMenuTreeResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.allAuthority = result.data.allAuthorityList;
      this.roleAuthority = result.data.roleAuthorityList;
      this.menuAuthorityTree = this.authorityTree(result.data.allAuthorityList, result.data.roleAuthorityList);
      this.initRoleAuthorizationZTree(this.menuAuthorityTree);
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }

  /**
   *
   * @param allAuthority
   * @param roleAuthority
   * @returns {Array}
   */
  private authorityTree(allAuthority, roleAuthority): any[] {
    if (roleAuthority) {
      $.each(allAuthority, function(allIndex, allAuth){
        //已被授权的权限
        $.each(roleAuthority, function(roleIndex, roleAuth){
          //如果已被授权，初始化时勾选
          if (roleAuth.id == allAuth.id) {
            allAuth.checked = true;
          }
        });
      });
    }

    //定义空数组
    // var defaultNodes = [];

    //过滤操作和资源
    // $.each(allAuthority, function (allIndex, nv) {
    //   if (nv.authority_config_id != "4" && nv.authority_config_id != "3") {
    //     if(nv.authority_config_id == "2"){
    //       //修改笔标识
    //       // nv.icon = "/assets/imgs/portal/pencil.png;"
    //     }else{
    //       // nv.isParent = true;
    //     }
    //     defaultNodes.push(nv);
    //   }
    // });

    return allAuthority;
  }


  /**
   * 实现添加
   */
  saveRoleAuthorization() {
    this.processingSelectedData();
    if(!!this.roleId&&!!this.role_authorty_id){
      this.rolesService.saveAssignAuthority(this.roleId,this.role_authorty_id).subscribe(
        result =>this.responseUtil.success(result,this.processRoleAuthorityResult),
        message =>this.responseUtil.error(message)
      );
    }
  }

  /**
   * 处理勾中复选框数据
   */
  processingSelectedData(){
    let treeObj = $.fn.zTree.getZTreeObj("character-allot-tree");
    let nodes = treeObj.getCheckedNodes();
    for(var i = 0; i < nodes.length; i++){
      this.role_authorty_id.push(nodes[i].id + "|" +nodes[i].authorityConfigId);
    }
  }

  /**
   * 获取角色授权日志
   * @param result
   */
  private processRoleAuthorityResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      //清空数组
      this.role_authorty_id.splice(0, this.role_authorty_id.length);
      this.dialogService.modalSuccess("分配权限成功！", ()=>this.cancelRoleAuthorization());
    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
      //清空数组
      this.role_authorty_id.splice(0, this.role_authorty_id.length);
    }
  }

  /**
   * 取消添加
   */
  cancelRoleAuthorization() {
    if (!!this.route.snapshot.params["aRId"]){
      this.router.navigate(['../../accounts',{mid:this.menuId}], {relativeTo: this.route});
    }else{
      this.router.navigate(['..'], {relativeTo: this.route});
    }
  }

  /**
   * 实例化对象
   */
  private initObject() {
    this.role = new Role("", "", "", "", "", "", "");
  }

  /**
   *
   * @param menus
   * @param authorityConfigId  :,authorityConfigId
   */
  initRoleAuthorizationZTree(menus) {
    var zNodes = menus;

    var setting = {
      check: {
        enable: true,
        // chkboxType :{ "Y" : "s", "N" : "s" }
        // chkboxType :{ "Y" : "ps", "N" : "ps"}
        chkboxType :{ "Y" : "ps", "N" : "s" }
      },
      view: {
        dblClickExpand: true,
        selectedMulti:true
      },
      data: {
        simpleData: {
          enable: true
        }
      },

      callback: {
      },

    };

    //把树放进页面
    $.fn.zTree.init($("#character-allot-tree"), setting, zNodes);
  }

}
